package com.elinkway.infinitemovies.adapter;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.elinkway.infinitemovies.adaction.CommonAdActionHandle;
import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.async.ThirdAdReportTask;
import com.elinkway.infinitemovies.bean.OnePointDataBean;
import com.elinkway.infinitemovies.bean.OnePointItemBean;
import com.elinkway.infinitemovies.bigdata.BigDataConstants;
import com.elinkway.infinitemovies.dao.PreferencesManager;
import com.elinkway.infinitemovies.selfdata.MyDataRecordCreater;
import com.elinkway.infinitemovies.selfdata.bean.OnePointRecord;
import com.elinkway.infinitemovies.selfdata.dao.RealmDaoManager;
import com.elinkway.infinitemovies.ui.activity.play.PlayActivityFroWebView;
import com.elinkway.infinitemovies.ui.activity.play.PlayerUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.MoviesUtils;
import com.elinkway.infinitemovies.utils.ReportUtil;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.utils.Utils;
import com.le123.ysdq.R;
import com.le123.ysdq.databinding.LayoutOnepointAdOnepicBinding;
import com.le123.ysdq.databinding.LayoutOnepointAdThreepicBinding;
import com.le123.ysdq.databinding.LayoutOnepointVideoBigBinding;
import com.le123.ysdq.databinding.LayoutOnepointVideoSmallBinding;
import com.le123.ysdq.databinding.LayoutRefreshTipsBinding;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

/**
 * Created by xiao on 8/23/17.
 */
public class OnePointAdapter extends RecyclerListAdapter {

    public static final String TAG = "OnePointAdapter";

    private LayoutInflater mLayoutInflater;
    private Context mContext;
    private static ImageLoader imageloader;
    private static String userid;
    private static String fromid;

    public OnePointAdapter(final Context mContext, ArrayList onePointItemList) {
        this.mContext = mContext;
        this.mItemList = onePointItemList;
        mLayoutInflater = LayoutInflater.from(mContext);
        imageloader = ImageLoader.getInstance();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        if (viewType == MoviesConstant.ONEPOINT_VIDEO_SMALL) {
            return new VideoSmallHolder(mLayoutInflater.inflate(R.layout.layout_onepoint_video_small, viewGroup, false));
        } else if (viewType == MoviesConstant.ONEPOINT_VIDEO_BIG) {
            return new VideoBigHolder(mLayoutInflater.inflate(R.layout.layout_onepoint_video_big, viewGroup, false));
        } else if (viewType == MoviesConstant.ONEPOINT_AD_ONEPIC) {
            return new AdOnepicHolder(mLayoutInflater.inflate(R.layout.layout_onepoint_ad_onepic, viewGroup, false));
        } else if (viewType == MoviesConstant.ONEPOINT_AD_THREEPIC) {
            return new AdThreepicHolder(mLayoutInflater.inflate(R.layout.layout_onepoint_ad_threepic, viewGroup, false));
        } else if(viewType == MoviesConstant.ONEPOINT_REFRESH_TIPS){
            return new RefreshTipsHolder(mLayoutInflater.inflate(R.layout.layout_refresh_tips, viewGroup, false));
        }else {
            return new VideoSmallHolder(mLayoutInflater.inflate(R.layout.layout_onepoint_video_small, viewGroup, false));
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof VideoSmallHolder) {
            ((VideoSmallHolder) holder).bind((OnePointItemBean) mItemList.get(position), mContext);
        } else if (holder instanceof VideoBigHolder) {
            ((VideoBigHolder) holder).bind((OnePointItemBean) mItemList.get(position), mContext);
        } else if(holder instanceof AdOnepicHolder) {
            ((AdOnepicHolder) holder).bind((OnePointItemBean) mItemList.get(position), mContext);
        } else if(holder instanceof AdThreepicHolder) {
            ((AdThreepicHolder) holder).bind((OnePointItemBean) mItemList.get(position), mContext);
        } else if(holder instanceof RefreshTipsHolder){
            ((RefreshTipsHolder) holder).bind((String) mItemList.get(position), mContext);
        }else  {

        }
    }

    @Override
    public int getItemViewType(int position) {
        Object obj = mItemList.get(position);
        if (obj instanceof OnePointItemBean) {
            OnePointItemBean itemBean = (OnePointItemBean) obj;
            if("video".equals(itemBean.ctype)){
                if("1".equals(itemBean.imageType)){
                    return MoviesConstant.ONEPOINT_VIDEO_BIG;
                }else{
                    return MoviesConstant.ONEPOINT_VIDEO_SMALL;
                }
            }else if("advertisement".equals(itemBean.ctype)){
                if("4".equals(itemBean.template) || "25".equals(itemBean.template)){
                    return MoviesConstant.ONEPOINT_AD_ONEPIC;
                }else if("40".equals(itemBean.template) || "31".equals(itemBean.template)){
                   return MoviesConstant.ONEPOINT_AD_THREEPIC;
                }else{
                    return MoviesConstant.ONEPOINT_AD_ONEPIC;
                }
            }else{
                return MoviesConstant.ONEPOINT_VIDEO_SMALL;
            }
        }else if(obj instanceof String){
            return MoviesConstant.ONEPOINT_REFRESH_TIPS;
        }else{
            return MoviesConstant.ONEPOINT_VIDEO_SMALL;
        }
    }

    public static class VideoSmallHolder extends RecyclerView.ViewHolder {
        private LayoutOnepointVideoSmallBinding mVideoSmallBinding;

        public VideoSmallHolder(View itemView) {
            super(itemView);
            mVideoSmallBinding = DataBindingUtil.bind(itemView);
        }

        public void bind(@NonNull final OnePointItemBean itemBean, final Context context) {
            mVideoSmallBinding.setItem(itemBean);
            imageloader.displayImage(itemBean.image, mVideoSmallBinding.onepointItemPoster);
            if(!TextUtils.isEmpty(itemBean.play_count)){
                mVideoSmallBinding.videoPlayCountTv.setText(changeCount(itemBean.play_count));
            }else{
                mVideoSmallBinding.videoPlayCountTv.setText("");
            }
            if(itemBean.duration > 0){
                mVideoSmallBinding.videoDurationTv.setText(PlayerUtils.toStringTime((int) itemBean.duration*1000));
                mVideoSmallBinding.videoDurationTv.setVisibility(View.VISIBLE);
            }else{
                mVideoSmallBinding.videoDurationTv.setVisibility(View.GONE);
            }
            mVideoSmallBinding.onepointItemLl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!TextUtils.isEmpty(itemBean.url)){
                        jumpReport(itemBean);

//                        Utils.jumpWebViewActivity(context,itemBean.url,"");
                        Intent intent = new Intent(context, PlayActivityFroWebView.class);
                        String url = itemBean.url.concat("&auid="+BigDataConstants.AUID);
                        intent.putExtra("url", url);
                        intent.putExtra("title", itemBean.title);
                        intent.putExtra("pic", itemBean.image);
                        intent.putExtra("from", MoviesConstant.ONEPOINT_TAG);
                        intent.putExtra("totype", "video");
                        intent.putExtra("summary", itemBean.summary);

                        intent.putExtra("pageid", itemBean.pageid);
                        intent.putExtra("impid", itemBean.impid);
                        intent.putExtra("docid", itemBean.docid);
                        intent.putExtra("userid", userid);
                        context.startActivity(intent);
                    }
                }
            });
            mVideoSmallBinding.videoSourceTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sourceReport(itemBean);
                    if(itemBean.wemedia_info != null && !TextUtils.isEmpty(itemBean.wemedia_info.wemedia_url)){
//                        Utils.jumpOnePointWebViewActivity(context, itemBean.wemedia_info.wemedia_url,"");
                        Intent intent = new Intent(context, PlayActivityFroWebView.class);
                        String url = itemBean.wemedia_info.wemedia_url.concat("&auid="+BigDataConstants.AUID);
                        intent.putExtra("url", url);
                        intent.putExtra("title", itemBean.source);
                        intent.putExtra("pic", itemBean.wemedia_info.image);
                        intent.putExtra("from", MoviesConstant.ONEPOINT_TAG);
                        intent.putExtra("totype", "author");
                        context.startActivity(intent);

                    }
                }
            });
        }
    }

    //上报：短视频点击跳转
    private static void jumpReport(@NonNull OnePointItemBean itemBean) {
        //上报：短视频流内点击
        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject.put("userid",userid);
            jsonObject.put("pageid",itemBean.pageid);
            jsonObject.put("impid",itemBean.impid);
            jsonObject.put("srcType","1");
            jsonObject.put("actionSrc","list");
            jsonObject.put("docid",itemBean.docid);
            jsonObject.put("subType","clickDoc");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ReportUtil.report(jsonObject);

        UmengEventPoster.doEventPost(BigDataConstants.CLICKVIDEOCARD);

        OnePointRecord record = MyDataRecordCreater.build(OnePointRecord.class);
        record.setAcode("0");
        record.setCur_url("VideoClips");
        record.setVideoClipsId(itemBean.docid);
        RealmDaoManager.addMyDataRecord(record);
    }
    //上报：视频来源点击
    private static void sourceReport(@NonNull OnePointItemBean itemBean) {
        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject.put("userid",userid);
            jsonObject.put("pageid",itemBean.pageid);
            jsonObject.put("impid",itemBean.impid);
            jsonObject.put("srcType","1");
//            jsonObject.put("actionSrc","pagechannel");
            jsonObject.put("docid",itemBean.docid);
            jsonObject.put("subType","wemedia");
            jsonObject.put("channel_from_id",getFromid());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ReportUtil.report(jsonObject);

        OnePointRecord record = MyDataRecordCreater.build(OnePointRecord.class);
        record.setAcode("0");
        record.setCur_url("VideoClips");
        record.setFromId(itemBean.wemedia_info.fromId);
        RealmDaoManager.addMyDataRecord(record);
    }

    public static class VideoBigHolder extends RecyclerView.ViewHolder {
        private LayoutOnepointVideoBigBinding mVideoBigBinding;

        public VideoBigHolder(View itemView) {
            super(itemView);
            mVideoBigBinding = DataBindingUtil.bind(itemView);
        }

        public void bind(@NonNull final OnePointItemBean itemBean, final Context context) {
            mVideoBigBinding.videoToPlayTv.setVisibility(View.GONE);
            mVideoBigBinding.setItem(itemBean);
            imageloader.displayImage(itemBean.image, mVideoBigBinding.onepointItemPoster,new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String s, View view) {
                }

                @Override
                public void onLoadingFailed(String s, View view, FailReason failReason) {
                }

                @Override
                public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                    mVideoBigBinding.videoToPlayTv.setVisibility(View.VISIBLE);
                }

                @Override
                public void onLoadingCancelled(String s, View view) {
                }
            });
            if(!TextUtils.isEmpty(itemBean.play_count)){
                mVideoBigBinding.videoPlayCountTv.setText(changeCount(itemBean.play_count));
            }else{
                mVideoBigBinding.videoPlayCountTv.setText("");
            }

            if(itemBean.duration > 0){
                mVideoBigBinding.videoDurationTv.setText(PlayerUtils.toStringTime((int) itemBean.duration*1000));
                mVideoBigBinding.videoDurationTv.setVisibility(View.VISIBLE);
            }else{
                mVideoBigBinding.videoDurationTv.setVisibility(View.GONE);
            }

            mVideoBigBinding.onepointItemRl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!TextUtils.isEmpty(itemBean.url)){
                        jumpReport(itemBean);
//                        Utils.jumpWebViewActivity(context,itemBean.url,"");
                        Intent intent = new Intent(context, PlayActivityFroWebView.class);
                        String url = itemBean.url.concat("&auid="+BigDataConstants.AUID);
                        intent.putExtra("url", url);
                        intent.putExtra("title", itemBean.title);
                        intent.putExtra("pic", itemBean.image);
                        intent.putExtra("from", MoviesConstant.ONEPOINT_TAG);
                        intent.putExtra("totype", "video");
                        intent.putExtra("summary", itemBean.summary);

                        intent.putExtra("pageid", itemBean.pageid);
                        intent.putExtra("impid", itemBean.impid);
                        intent.putExtra("docid", itemBean.docid);
                        intent.putExtra("userid", userid);
                        context.startActivity(intent);
                    }
                }
            });
            mVideoBigBinding.videoSourceTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sourceReport(itemBean);
                    if(itemBean.wemedia_info != null && !TextUtils.isEmpty(itemBean.wemedia_info.wemedia_url)){
//                        Utils.jumpWebViewActivity(context, itemBean.wemedia_info.wemedia_url,"");
                        Intent intent = new Intent(context, PlayActivityFroWebView.class);
                        String url = itemBean.wemedia_info.wemedia_url.concat("&auid="+BigDataConstants.AUID);
                        intent.putExtra("url", url);
                        intent.putExtra("title", itemBean.source);
                        intent.putExtra("pic", itemBean.wemedia_info.image);
                        intent.putExtra("from", MoviesConstant.ONEPOINT_TAG);
                        intent.putExtra("totype", "author");
                        context.startActivity(intent);

                    }
                }
            });
        }
    }

    public static class AdOnepicHolder extends RecyclerView.ViewHolder {
        private LayoutOnepointAdOnepicBinding mAdOnepicBinding;

        public AdOnepicHolder(View itemView) {
            super(itemView);
            mAdOnepicBinding = DataBindingUtil.bind(itemView);
        }

        public void bind(@NonNull final OnePointItemBean itemBean, final Context context) {
            mAdOnepicBinding.setItem(itemBean);
            imageloader.displayImage(itemBean.image, mAdOnepicBinding.onepointItemPoster);
            if("25".equals(itemBean.template)){//下载
                mAdOnepicBinding.onepointAdDownloadTv.setVisibility(View.VISIBLE);
            }else{
                mAdOnepicBinding.onepointAdDownloadTv.setVisibility(View.GONE);
            }
            mAdOnepicBinding.onepointItemLl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!TextUtils.isEmpty(itemBean.url)){
                        reportOnePointAd(context, itemBean.clickMonitorUrls);
                        if(!TextUtils.isEmpty(itemBean.deepLinkUrl)){
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(itemBean.deepLinkUrl));
                            if (Utils.deviceCanHandleIntent(context, intent)) {
                                context.startActivity(intent);
                            } else {
                                CommonAdActionHandle.getInstance().go2WebView(context, itemBean.url);
                            }
                        }else{
                            CommonAdActionHandle.getInstance().go2WebView(context, itemBean.url);
                        }
                    }
                }
            });
            mAdOnepicBinding.onepointAdDownloadTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!TextUtils.isEmpty(itemBean.actionUrl)){
                        CommonAdActionHandle.getInstance().downloadApp(context, itemBean.pn, itemBean.source, "",
                                itemBean.actionUrl, itemBean.deepLinkUrl, itemBean.stdMonitorUrls, itemBean.fidMonitorUrls,
                                null, null);
                    }
                }
            });
            reportOnePointAd(context, itemBean.viewMonitorUrls);
        }
    }

    public static class AdThreepicHolder extends RecyclerView.ViewHolder {
        private LayoutOnepointAdThreepicBinding mAdThreepicBinding;

        public AdThreepicHolder(View itemView) {
            super(itemView);
            mAdThreepicBinding = DataBindingUtil.bind(itemView);
        }

        public void bind(@NonNull final OnePointItemBean itemBean, final Context context) {
            mAdThreepicBinding.setItem(itemBean);
            if(itemBean.image_urls != null){
                for (int i=0;i<itemBean.image_urls.size();i++){
                    if(!TextUtils.isEmpty(itemBean.image_urls.get(i))){
                        if(i == 0){
                            imageloader.displayImage(itemBean.image_urls.get(i), mAdThreepicBinding.onepointItemPosterOne);
                        }else if(i == 1){
                            imageloader.displayImage(itemBean.image_urls.get(i), mAdThreepicBinding.onepointItemPosterTwo);
                        }else if(i == 2){
                            imageloader.displayImage(itemBean.image_urls.get(i), mAdThreepicBinding.onepointItemPosterThree);
                        }
                    }
                }
            }
            if("31".equals(itemBean.template)){//下载
                mAdThreepicBinding.onepointAdDownloadTv.setVisibility(View.VISIBLE);
            }else{
                mAdThreepicBinding.onepointAdDownloadTv.setVisibility(View.GONE);
            }
            mAdThreepicBinding.onepointItemRl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!TextUtils.isEmpty(itemBean.url)){
                        reportOnePointAd(context, itemBean.clickMonitorUrls);
                        if(!TextUtils.isEmpty(itemBean.deepLinkUrl)){
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(itemBean.deepLinkUrl));
                            if (Utils.deviceCanHandleIntent(context, intent)) {
                                context.startActivity(intent);
                            } else {
                                CommonAdActionHandle.getInstance().go2WebView(context, itemBean.url);
                            }
                        }else{
                            CommonAdActionHandle.getInstance().go2WebView(context, itemBean.url);
                        }
                    }
                }
            });
            mAdThreepicBinding.onepointAdDownloadTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!TextUtils.isEmpty(itemBean.actionUrl)){
                        CommonAdActionHandle.getInstance().downloadApp(context, itemBean.pn, itemBean.source, "",
                                itemBean.actionUrl, itemBean.deepLinkUrl, itemBean.stdMonitorUrls, itemBean.fidMonitorUrls,
                                null, null);
                    }
                }
            });
            reportOnePointAd(context, itemBean.viewMonitorUrls);
        }
    }

    public static class RefreshTipsHolder extends RecyclerView.ViewHolder {
        private LayoutRefreshTipsBinding mRefreshTipsBinding;

        public RefreshTipsHolder(View itemView) {
            super(itemView);
            mRefreshTipsBinding = DataBindingUtil.bind(itemView);
        }

        public void bind(@NonNull final String tips, final Context context) {
            mRefreshTipsBinding.itemRefreshTipsTv.setText(tips);
        }
    }

    private static String changeCount(String count){
        long num = 0;
        String showCount = "";
        try {
           num = Long.parseLong(count);
        }catch (Exception e){

        }
        if(num >= 10000000){
            showCount = "1千万次播放";
        } else if (num >= 100000) {
            showCount = num/10000 + "万次播放";
        }else if (num >=10000){
            showCount = num/10000+"."+(num/1000)%10+"万次播放";
        }else if(num > 0){
            showCount = num+"次播放";
        }
        return showCount;
    }

    private static void reportOnePointAd(Context context, ArrayList<String> list){
        if(list != null && list.size() > 0){
            for (int i=0;i<list.size();i++){
                String oneReportUrl = list.get(i);
                if(!TextUtils.isEmpty(oneReportUrl)){
                    oneReportUrl = oneReportUrl.replace("__OS__", "0").replace("__IP__", PreferencesManager.getInstance().getPublicIp()).replace("__IMEI__", BigDataConstants.MD5IMEI)
                            .replace("__MAC__",BigDataConstants.UPMD5MAC).replace("__ANDROIDID__", BigDataConstants.MD5ANDROIDID).replace("__AndroidID__", BigDataConstants.MD5ANDROIDID)
                            .replace("__TS__",System.currentTimeMillis()+"").replace("__TERM__", MoviesUtils.getDeviceModel()).replace("__APP__", URLEncoder.encode(MoviesUtils.getAppName(context)));
                    new ThirdAdReportTask(context, oneReportUrl, Utils.getBrowserUa(context)).start();
                }
            }
        }
    }

    public String getUserid() {
        return userid;
    }

    public void setUserid(String userid) {
        this.userid = userid;
    }

    public static String getFromid() {
        return fromid;
    }

    public static void setFromid(String fromid) {
        OnePointAdapter.fromid = fromid;
    }
}

